<template>
  <div class="editDialog">
    <el-dialog
      :close-on-click-modal="false"
      :title="dialogData.title === 'add' ? '新增' : '编辑'"
      :visible.sync="dialogData.isShow"
      :before-close="closeDialog"
      width="80%"
    >
      <!-- 搜索 -->
      <el-form :model="searchInfo" ref="search" :rules="rules" :inline="true">
        <el-form-item label="" prop="type">
          <el-select
            v-model="coursetable"
            placeholder="排课管理"
            size="small"
            @change="checkCourse"
            clearable
          >
            <el-option
              v-for="item in courseClassify"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="" prop="collegeId">
          <el-select
            v-model="searchInfo.type"
            placeholder="课程类型"
            size="small"
            clearable
          >
            <el-option
              v-for="item in courseTypeList"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="" prop="status">
          <el-select
            v-model="searchInfo.collegeId"
            placeholder="所属学院"
            size="small"
            clearable
          >
            <el-option
              v-for="item in collegeList"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="" prop="type">
          <el-select
            v-model="searchInfo.status"
            placeholder="课程状态"
            size="small"
            clearable
          >
            <el-option
              v-for="item in courseStateList"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="" prop="name">
          <el-input
            v-model="searchInfo.name"
            placeholder="输入课程名称"
            size="small"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item class="s-btn">
          <el-button
            type="success"
            icon="el-icon-search"
            @click="toSearch('search')"
          >
            查询
          </el-button>
          <el-button type="success" plain @click="resetSearch('search')">
            重置
          </el-button>
        </el-form-item>
      </el-form>
      <!-- 表格 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-table
            v-loading="loading"
            :data="tableData"
            ref="multipleTable"
            header-cell-class-name="tab-head"
            @select="selectionChange"
            height="490"
          >
            <el-table-column
              type="selection"
              width="55"
              align="center"
              :selectable="checkboxs"
            >
            </el-table-column>
            <el-table-column
              prop="name"
              label="课程名称"
              align="center"
            ></el-table-column>
            <el-table-column label="课程类型" align="center">
              <template slot-scope="scope">
                <span :class="scope.row.type | filterClass('courseType')">{{
                  scope.row.type | filterName('courseType')
                }}</span>
              </template>
            </el-table-column>
            <el-table-column label="所属学院" width="120" align="center">
              <template slot-scope="scope" v-if="scope.row.college">
                <span>{{ scope.row.college.name }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="globalState"
              label="课程状态"
              width="100"
              align="center"
            >
              <template slot-scope="scope">
                <span
                  class="tag-span"
                  :class="scope.row.status | filterClass('courseState')"
                  >{{ scope.row.status | filterName('courseState') }}</span
                >
              </template>
            </el-table-column>
          </el-table>
          <!--分页-全局组件-->
          <pageCom
            :searchParams="searchParams"
            :total="total"
            @searchList="searchCourseList"
          ></pageCom>
        </el-col>
        <el-col :span="12">
          <!-- 表格部分 -->
          <el-table
            v-loading="loadingRight"
            header-cell-class-name="tab-head"
            :data="showCheckData"
            height="490"
          >
            <el-table-column
              type="index"
              label="序号"
              align="center"
            ></el-table-column>
            <el-table-column
              align="center"
              prop="name"
              label="课程名称"
            ></el-table-column>
            <el-table-column label="课程类型" align="center">
              <template slot-scope="scope">
                <span :class="scope.row.type | filterClass('courseType')">{{
                  scope.row.type | filterName('courseType')
                }}</span>
              </template>
            </el-table-column>
            <el-table-column label="所属学院" width="120" align="center">
              <template slot-scope="scope">
                <span v-if="scope.row.college">{{
                  scope.row.college.name
                }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="70" align="center">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  @click="delCheck(scope.row, 'clickDelete')"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <!--分页-全局组件-->
          <pageCom
            :searchParams="searchParamsRight"
            :total="totalRight"
            @searchList="searchListRight"
          ></pageCom>
        </el-col>
      </el-row>
      <!-- 快捷消息 -->
      <div class="the-message">
        <el-form
          :model="swiftMessage"
          ref="swiftMessage"
          :rules="rules"
          :inline="true"
        >
          <el-form-item label="快捷消息：" prop="message">
            <el-input
              v-model.trim="swiftMessage.message"
              placeholder="输入消息名称"
              size="small"
              maxlength="8"
              show-word-limit
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item class="s-btn">
            <el-button type="success" @click="addSwiftMessage('swiftMessage')"
              >添加</el-button
            >
          </el-form-item>
        </el-form>
        <el-tag
          type="info"
          closable
          @close="deleteMessage(item.message)"
          v-for="(item, index) in messagesList"
          :key="index"
          style="margin-right: 5px;"
          >{{ item.message }}</el-tag
        >
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="success" plain @click="closeDialog">取 消</el-button>
        <el-button type="success" @click="sbumitMessge()">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { sysNormalDisable } from '@utils/dictionariesFunc'
import {
  getCourseList,
  getWindowCourses,
  addMessage,
  getRelatedCourses,
  getMessageCourseDetail,
  getMessageDetail,
  updataMessage
} from '@/api/appSetting/swiftMessage'
export default {
  props: ['dialogData', 'collegeList'],
  data() {
    return {
      loading: false,
      loadingRight: false,
      courseClassify: [
        { name: '排课管理', value: 'course_type_formal' },
        { name: '橱窗试学课', value: 'course_type_trial' }
      ],
      coursetable: '',
      courseTypeList: [],
      courseStateList: [],
      tableData: [], //所有课程
      showCheckData: [], //已选课程
      swiftMessage: {
        message: ''
      },
      messagesList: [],
      courses: [], //课程信息
      relatedCourses: [], //已关联消息的课程
      total: 0,
      totalRight: 0,
      searchInfo: {
        type: '',
        collegeId: '',
        status: '',
        name: ''
      },
      searchParams: {
        pageNum: 1, // 当前页数
        pageSize: 10 // 页面显示条数
      },
      searchParamsRight: {
        id: '',
        pageNum: 1, // 当前页数
        pageSize: 10 // 页面显示条数
      },
      rules: {
        name: [{ min: 2, message: '最少输入2个关键字查询', trigger: 'blur' }],
        message: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.coursetable = 'course_type_formal' //默认排课管理
    this.checkCourse(this.coursetable) //课程类型
    this.searchParams.pageNum = 1
    this.searchCourseList() //课程列表
    this.relatedCoursesAll() //已关联消息的课程
    if (this.dialogData.title === 'edit') {
      this.searchListRight(this.dialogData) //右侧tabla
    }
  },
  methods: {
    /* 获取课程 */
    searchCourseList() {
      const { coursetable } = this
      if (coursetable === 'course_type_formal') {
        getCourseList(this.searchParams, (response) => {
          this.tableData = response.rows
          this.total = response.total
        })
      } else {
        getWindowCourses(this.searchParams, (response) => {
          this.tableData = response.rows
          this.total = response.total
        })
      }
    },
    /* 编辑时数据 */
    searchListRight(val) {
      this.searchParamsRight.id = val.id
      getMessageCourseDetail(val, (response) => {
        this.showCheckData = response.rows
        this.totalRight = response.total
        this.showCheckData.forEach((item) => {
          this.courses.push({
            collegeId: item.college.id,
            courseId: item.id
          })
        })
      })
      getMessageDetail(val, (response) => {
        response.forEach((item) => {
          item = { message: item }
          this.messagesList.push(item)
        })
      })
    },
    /* 所有已关联消息的课程 */
    relatedCoursesAll() {
      getRelatedCourses({}, (res) => {
        this.relatedCourses = res
        this.defaultCheck()
      })
    },
    /* 默认选中 */
    defaultCheck() {
      this.showCheckData.forEach((item) => {
        this.tableData.forEach((el) => {
          if (el.id === item.id) {
            this.$nextTick(() => {
              this.$refs.multipleTable.toggleRowSelection(el)
            })
          }
        })
      })
    },
    /* 课程类型 */
    async checkCourse(val) {
      this.searchInfo = {}
      if (val === 'course_type_formal') {
        this.courseTypeList = await sysNormalDisable('course_type_formal')
      } else {
        this.courseTypeList = await sysNormalDisable('course_type_trial')
        this.searchInfo.type = 'TRIAL'
      }
      //课程状态
      this.courseStateList = await sysNormalDisable('course_status')
    },
    /* 点击查询 */
    toSearch(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.searchParams = { ...this.searchInfo, pageNum: 1, pageSize: 10 }
          this.searchCourseList()
          this.relatedCoursesAll()
        } else {
          return false
        }
      })
    },
    /* 点击重置 */
    resetSearch(formName) {
      this.$refs[formName].resetFields()
      this.coursetable = 'course_type_formal'
      this.checkCourse(this.coursetable)
    },
    /*手动勾选*/
    selectionChange(selection, row) {
      const addOrReduce = this.showCheckData.some((item) => {
        return item.id === row.id
      })
      if (addOrReduce) {
        this.delCheck(row)
      } else {
        this.addCheck(row)
      }
    },
    /* 增加已选课程 */
    addCheck(row) {
      this.showCheckData.push(row)
      this.courses.push({
        collegeId: row.college ? row.college.id : '',
        courseId: row.id
      })
    },
    /* 删除已选课程 */
    delCheck(row, val) {
      let index = this.showCheckData.findIndex((item) => {
        return item.id == row.id
      })
      this.showCheckData.splice(index, 1)
      let relatedIndex = this.relatedCourses.findIndex((item) => {
        return item.id === row.id
      })
      this.relatedCourses.splice(relatedIndex, 1)
      this.courses.splice(index, 1)
      if (val === 'clickDelete') {
        const tableDataRow = this.tableData.find((item) => {
          return item.id === row.id
        })
        this.$refs.multipleTable.toggleRowSelection(tableDataRow)
      }
    },
    /* 添加快捷消息 */
    addSwiftMessage(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const res = this.messagesList.some((item) => {
            return item.message === this.swiftMessage.message
          })
          if (res) {
            this.$message({
              message: '该消息已存在',
              type: 'warning'
            })
            this.swiftMessage.message = ''
            return
          }
          if (this.messagesList.length === 10) {
            this.$message({
              message: '快捷消息不能超过十条',
              type: 'warning'
            })
            this.swiftMessage.message = ''
            return
          }
          let messageObj = { message: this.swiftMessage.message }
          this.messagesList.push(messageObj)
          this.swiftMessage.message = ''
        } else {
          return false
        }
      })
    },
    /* 删除快捷消息 */
    deleteMessage(val) {
      let msgIndex = this.messagesList.findIndex((item) => item.message === val)
      this.messagesList.splice(msgIndex, 1)
    },
    /* 编辑禁用选中行 */
    checkboxs(row) {
      const condition = this.relatedCourses.some((el) => {
        return el.id === row.id
      })
      if (condition) {
        return false
      } else {
        return true
      }
    },
    /* 点击确定 */
    sbumitMessge() {
      const { messagesList, courses } = this
      let messages = []
      messagesList.forEach((item) => {
        messages.push(item.message)
      })
      if (this.dialogData.title === 'add') {
        addMessage({ messages, courses }, () => {
          this.$emit('sendMsg')
          Object.assign(this.$data, this.$options.data())
          this.dialogData.isShow = false
        })
      } else {
        updataMessage({ messages, courses, id: this.dialogData.id }, () => {
          this.$emit('sendMsg')
          Object.assign(this.$data, this.$options.data())
          this.dialogData.isShow = false
        })
      }
    },
    /* 点击取消 */
    closeDialog() {
      Object.assign(this.$data, this.$options.data())
      this.dialogData.isShow = false
    }
  }
}
</script>
<style lang="less" scoped>
:deep(.el-table__header-wrapper .el-checkbox) {
  display: none;
}
:deep(.el-dialog) {
  margin: 5vh auto 0 !important;
}
</style>
